﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <termios.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <linux/serio.h>
#include <linux/tty.h>
#include <linux/input.h>

#define N_IRKBD	(NR_LDISCS - 2)

static const char *TTY_DEV = "/dev/ttymxc1";
static bool bexit = false;

static void show_usage(char *arg0)
{
	printf("Usage : %s"
		"\t[--d ttydev] -- default to '/dev/ttymxc1'"
		"\t[-h]         -- show this help",
		arg0);
}

void signal_handle(int signo)
{
	bexit = true;
}

int main(int argc, char *argv[])
{
	int fd, res;
	char tty_dev[64];
	if(argc > 3) {
		show_usage(argv[0]);
		return 0;
	}

	strcpy(tty_dev, TTY_DEV);
	
	for(int i = 1; i < argc; i++) {
		if(!strcmp(argv[i], "-d")) {
			if((i + 1) < argc && !strncmp(argv[i + 1], TTY_DEV, 8)) {
				strcpy(tty_dev, argv[i + 1]);
				i += 1;
			}
		} else if(!strcmp(argv[i], "-h")) {
			show_usage(argv[0]);
			return 0;
		}
	}
	
	daemon(0, 0);
	signal(SIGINT, signal_handle);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, SIG_IGN);
	
	fd = open(tty_dev, O_RDWR | O_NOCTTY/* | O_NDELAY*/);
	// fd = open("/dev/ttymxc1", O_RDWR | O_NOCTTY);
	if(fd < 0) {
		perror("open uart");
		return fd;
	}

	if(isatty(fd) == 0) {
		perror("isatty");
	}
	
	struct termios t;
	tcgetattr(fd, &t);
	t.c_cflag &= ~CSIZE;
	t.c_cflag &= ~CRTSCTS;
	t.c_cflag &= ~PARENB;
	t.c_iflag &= ~INPCK;
	t.c_cflag &= ~CSTOPB;
	t.c_cflag |= CREAD | HUPCL | CLOCAL | CS8;
	t.c_iflag = IGNBRK | IGNPAR;
	t.c_oflag = 0;
	t.c_lflag = 0;
	t.c_cc[VMIN] = 1;
	t.c_cc[VTIME] = 0;

	cfsetispeed(&t, B9600);
	cfsetospeed(&t, B9600);
	tcsetattr(fd, TCSANOW, &t);
	
	printf("App set ldisc\n");
	
	int ldisc = N_IRKBD;
	if (ioctl(fd, TIOCSETD, &ldisc)) {
		fprintf(stderr, "Can't set ldisc\n");
		close(fd);
		return 1;
	}

	char dummy[64];
	while(!bexit) {
		int rlen = read(fd, &dummy, 64);
		if(rlen > 0) {
		} else {
			sleep(1);
		}
	}

	close(fd);
	return 0;
}

